package com.mybatis.lo.handler;

import com.mybatis.lo.config.MappedStatement;
import com.mybatis.lo.mapping.BoundSql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 通过BoundSql获取到sql，存在符号`?`的参数需要进行预处理的处理器
 * @author zhangbh
 * 2023-06-20 08:35
 **/
public class PreparedStatementHandler implements StatementHandler {

    private final MappedStatement mappedStatement;
    private final ParameterHandler parameterHandler;
    private final ResultSetHandler resultSetHandler;
    private final BoundSql boundSql;
    private final Object param;

    public PreparedStatementHandler(MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultSetHandler resultSetHandler, BoundSql boundSql, Object param) {
        this.mappedStatement = mappedStatement;
        this.parameterHandler = parameterHandler;
        this.resultSetHandler = resultSetHandler;
        this.boundSql = boundSql;
        this.param = param;
    }

    @Override
    public Statement prepare(Connection connection) throws SQLException {
        System.out.println("查询sql=[" + boundSql.getSql() + "],查询参数=" + boundSql.getParameterMappings());
        return connection.prepareStatement(boundSql.getSql());
    }

    @Override
    public void parameterize(Statement statement) throws SQLException {
        parameterHandler.setParameters((PreparedStatement) statement);
    }

    @Override
    public <T> List<T> query(Statement statement) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.handleResultSets(ps);
    }
}
